#include "Medio.h"
#include "MiscData.h"
#include <QDir>
#include "FileUtility.h"
#include <unistd.h>
#include <fcntl.h>
#include <Database.h>
#ifdef arm
#include <sys/ioctl.h>

#include <QDateTime>
#include <QProcess>
#endif

Medio *Medio::getInstance()
{
    static Medio singleton{};
    return &singleton;
}

void Medio::init(QList<QLabel *>* imageLabels, QList<QLabel *>* videoLabels)
{
    g_imageLabels = imageLabels;
    g_imageLabelSize = g_imageLabels->size();
    g_videoLabels = videoLabels;
    g_videoLabelSize = g_videoLabels->size();
}

void Medio::updateMedio()
{
    updateImageMedio();
    updateVideoMedio();
}

/************************ image相关逻辑 ************************/
void Medio::updateImageMedio()
{
    updateImagePath();
    updateImageUi();
}

void Medio::updateImagePath()
{
    g_imagePathList.clear();
    /* 得到image路径: data/patient_x/image */
    QString imagePath = getCurrentPatientImagePath();
    QStringList pathList = FileUtility::getInstance()->findFile(imagePath, "*.jpg");
    QList<int> indexList;

    if (pathList.size() == 0)
        return;

    for (int i = 0; i < pathList.size(); i++) {
        indexList.append(pathList.at(i).split(".").at(0).toInt());
    }
    /* 从大到小排序 */
    std::sort(indexList.begin(), indexList.end(), std::greater<int>());
    for (int i = 0; i < indexList.size(); i++) {
        g_imagePathList.append(QString("%1.jpg").arg(indexList.at(i)));
    }

    for (int i = 0; i < g_imagePathList.size(); i++) {
        qDebug()<<QString("image [%1] = %2").arg(i).arg(g_imagePathList.at(i));
    }
}

void Medio::updateImageUi()
{
    QString path;
    QPixmap image;
    QLabel* label;

    /* 默认的image */
    for (int i = 0; i < g_imageLabelSize; i++) {
        label = g_imageLabels->at(i);
        image.load(":/image/image/defaultImage.png");
        label->setPixmap(image);
    }

    g_imageCurrentPagePathList.clear();
    if (g_imagePathList.isEmpty())
        return;

    QString imagePath = getCurrentPatientImagePath();
    int size = g_imagePathList.size() < g_imageLabelSize ? g_imagePathList.size() : g_imageLabelSize;
    for (int i = 0; i < size; i++) {
        label = g_imageLabels->at(i);
        path = QString("%1/%2").arg(imagePath).arg(g_imagePathList.at(i));
        g_imageCurrentPagePathList.append(path);
        image.load(path);
        label->setPixmap(image.scaled(label->width(),label->height()));
    }
}

QString Medio::getClickedImageLabelPath(QLabel *label)
{
    if (g_imageCurrentPagePathList.isEmpty())
        return "";

    for (int i = 0; i < g_imageLabels->size(); i++) {
        if (g_imageLabels->at(i) == label) {
            if (i >= g_imageCurrentPagePathList.size()) {
                return "";
            } else {
                return g_imageCurrentPagePathList.at(i);
            }
        }
    }

    return "";
}

QString Medio::getClickedVideoLabelPath(QLabel *label)
{
    if (g_videoCurrentPagePathList.isEmpty())
        return "";

    for (int i = 0; i < g_videoLabels->size(); i++) {
        if (g_videoLabels->at(i) == label) {
            if (i >= g_videoCurrentPagePathList.size()) {
                return "";
            } else {
                QString tmp = g_videoCurrentPagePathList.at(i);
                QString path = tmp.split(".").at(0);

                return path.append(".mp4");
            }
        }
    }

    return "";
}

QString Medio::getCurrentPatientNextImagePath()
{
    QString imagePath = getCurrentPatientImagePath();
    int lastIndex = -1;

    int size = g_imagePathList.size();
    if (size != 0) {
        QString lastPath = g_imagePathList.at(0);
        lastIndex = lastPath.split(".").at(0).toInt();;
    }

    QString newPath = QString("%1/%2.jpg").
                    arg(imagePath).
                    arg(QDateTime::currentDateTimeUtc().toString("yyyy-MM-dd_hh_mm_ss_zzz"));

    return newPath;
}

QString Medio::getCurrentPatientImagePath(int v)
{
    QString imagePath;

    int number = RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentApplyPatientNumber;
    if(v) number = RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentSelectPatientNumber;
    if (number < 0) {
        qDebug()<<"getCurrentPatientImagePath: system error";
        return "";
    }
    PatientInfo *info = Database::getInstance()->queryPatient(number);
    if (info->number < 0) {
        qDebug()<<"getCurrentPatientImagePath: system error";
        return "";
    }

    /* 构建image路径 */
    imagePath = QString("data/patient_%1/image").arg(info->id);
    QDir dir;
    if (!dir.exists(imagePath)) {
        if (!dir.mkpath(imagePath)){
            qDebug()<<"create dir faile:"<<imagePath;
            return "";
        } else {
            qDebug()<<"create dir succeed:"<<imagePath;
        }
    }

    /* 测试代码 */
//    imagePath = "data/patient_1/image";

    return imagePath;
}

/************************ video相关逻辑 ************************/
/* 没有.mp4后缀 */
QString Medio::getCurrentPatientNextVideoPath()
{
    QString videoPath = getCurrentPatientVideoPath();
    int lastIndex = -1;

    int size = g_videoPathList.size();
    if (size != 0) {
        QString lastPath = g_videoPathList.at(0);
        lastIndex = lastPath.split(".").at(0).toInt();;
    }

    QString newPath = QString("%1/%2").
                    arg(videoPath).
                    arg(QDateTime::currentDateTimeUtc().toString("yyyy-MM-dd_hh_mm_ss_zzz"));
    return newPath;
}

void Medio::deleteCurrentPatientMedio(int number)
{
#ifdef arm
    if(number<0) {
        qDebug()<<"getCurrentPatientImagePath: system error";
        return;
    }
    PatientInfo *info = Database::getInstance()->queryPatient(number);
    if (info->number < 0) {
        qDebug()<<"getCurrentPatientImagePath: system error";
        return;
    }
    QString path = QString("/home/root/data/patient_%1").arg(info->id);

    QStringList cmd;
    cmd << QString("rm %1 -rf").arg(path);
    QString command = cmd.join(";");

    int status = system(command.toUtf8().data());
    if((status < 0) || (!WIFEXITED(status)) || (0 != WEXITSTATUS(status))) {
        qDebug()<<"delete medio failed";return;
    }
    sync();
    //sleep(1);
#endif
}



void Medio::updateVideoMedio()
{
    updateVideoPath();
    updateVideoUi();
}

void Medio::updateVideoPath()
{
    g_videoPathList.clear();
    /* 得到video路径: data/patient_x/video */
    QString videoPath = getCurrentPatientVideoPath();
    QStringList pathList = FileUtility::getInstance()->findFile(videoPath, "*.jpg");
    QList<int> indexList;

    if (pathList.size() == 0)
        return;
    for (int i = 0; i < pathList.size(); i++) {
        indexList.append(pathList.at(i).split(".").at(0).toInt());
    }
    /* 从大到小排序 */
    std::sort(indexList.begin(), indexList.end(), std::greater<int>());
    for (int i = 0; i < indexList.size(); i++) {
        g_videoPathList.append(QString("%1.jpg").arg(indexList.at(i)));
    }

    for (int i = 0; i < g_videoPathList.size(); i++) {
        qDebug()<<QString("video [%1] = %2").arg(i).arg(g_videoPathList.at(i));
    }
}

void Medio::updateVideoUi()
{
    QString path;
    QPixmap video;
    QLabel* label;

    /* 默认的image */
    for (int i = 0; i < g_videoLabelSize; i++) {
        label = g_videoLabels->at(i);
        video.load(":/image/image/defaultImage.png");
        label->setPixmap(video);
    }
    QString videoPath = getCurrentPatientVideoPath();
    if (g_videoPathList.isEmpty())
        return;

    g_videoCurrentPagePathList.clear();
    int size = g_videoPathList.size() < g_videoLabelSize ? g_videoPathList.size() : g_videoLabelSize;
    for (int i = 0; i < size; i++) {
        label = g_videoLabels->at(i);
        path = QString("%1/%2").arg(videoPath).arg(g_videoPathList.at(i));
        g_videoCurrentPagePathList.append(path);
        video.load(path);
        label->setPixmap(video.scaled(label->width(),label->height()));
    }
}

QString Medio::getCurrentPatientVideoPath(int v)
{
    QString videoPath;

    int number = RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentApplyPatientNumber;
    if(v) number = RuntimeData::MiscData::getInstance()->g_miscDataInfo.currentSelectPatientNumber;
    if (number < 0) {
        qDebug()<<"getCurrentPatientVideoPath: system error";
        return "";
    }

    PatientInfo *info = Database::getInstance()->queryPatient(number);
    if (info->number < 0) {
        qDebug()<<"getCurrentPatientImagePath: system error";
        return "";
    }


    /* 构建video路径 */
    videoPath = QString("data/patient_%1/video").arg(info->id);
    QDir dir;
    if (!dir.exists(videoPath)) {
        if (!dir.mkpath(videoPath)){
            qDebug()<<"create dir faile:"<<videoPath;
            return "";
        } else {
            qDebug()<<"create dir succeed:"<<videoPath;
        }
    }

    /* 测试代码 */
//    videoPath = "data/patient_1/video";

    return videoPath;
}



Medio::Medio()
{

}
